var express = require('express');
var router = express.Router();
const { Model, Series } = require('../../models');
const { success, fail } = require('../../utils/response');
const { getModel } = require('../../utils/get-data');

router.get('/', async function(req, res, next) {
  try{
    let {page = 1, limit = 10} = req.query;
    page = parseInt(page);
    limit = parseInt(limit);
    const offset = (page - 1) * limit;
    const condition = {
      offset,
      limit,
      attributes: {
        exclude: ['SeriesId']
      },
      include: [
        {
          model: Series,
          as: 'series'
        }
      ]
    }
    const {count, rows: models} = await Model.findAndCountAll(condition);
    const data = {
      data: models,
      total: count,
      page,
      limit
    }
    success(res, data, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.get('/:id', async function(req, res, next) {
  try{
    const model = await getModel(req, res, next);
    success(res, model, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.post('/', async function(req, res, next) {
  try{
    const {seriesId, nameZh, nameEn, img, descriptionZh, descriptionEn, year, launchDate} = req.body;
    const model = await Model.create({seriesId, nameZh, nameEn, img, descriptionZh, descriptionEn, year, launchDate});
    success(res, model, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.put('/:id', async function(req, res, next) {
  try{
    const {seriesId, nameZh, nameEn, img, descriptionZh, descriptionEn, year, launchDate} = req.body;
    const model = await getModel(req, res, next);
    await model.update({seriesId, nameZh, nameEn, img, descriptionZh, descriptionEn, year, launchDate});
    success(res, model, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.delete('/:id', async function(req, res, next) {
  try{
    const model = await getModel(req, res, next);
    await model.destroy();
    success(res, null, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
module.exports = router;